package com.aiden.app.common.http.interceptor

import com.aiden.app.common.base.BaseApplication
import com.aiden.app.common.constant.ConfigConstants
import com.aiden.app.common.extension.isNotNil
import com.aiden.app.common.http.config.HttpGlobalConfig
import com.aiden.app.common.util.Encrypt
import com.aiden.app.common.util.LogUtils
import okhttp3.*
import org.json.JSONObject
import java.lang.StringBuilder
import java.util.*

/**
 * add common parameters and headers
 * @author yanggeng
 * @date 2018/12/12 15:08
 */
class HttpHeaderInterceptor(var params: Map<String, String>, var headers: Map<String, String>, var useCustomParams: Boolean = false) : Interceptor {

    private val TAG = HttpHeaderInterceptor::class.java.simpleName

    override fun intercept(chain: Interceptor.Chain?): Response {
        val oldRequest: Request = chain!!.request()

        val urlBuilder: HttpUrl.Builder = oldRequest.url().newBuilder()

        // 添加公共参数
        if (params.isNotEmpty()) {
            for (param in params) {
                urlBuilder.addQueryParameter(param.key, param.value)
            }
        }
        val requestBuilder = oldRequest.newBuilder()
        // 添加请求头
        if (!oldRequest.url().uri().toString().endsWith("loginApp") && !oldRequest.url().uri().toString().endsWith("getVerifyCodeWhenLogin") && headers.isNotEmpty()) {
            val headersBuilder = Headers.Builder()
            for (header in headers) {
                headersBuilder.set(header.key, header.value)
            }
            if (BaseApplication.INSTANCE.token.isNotNil()) {
                headersBuilder.set(
                    ConfigConstants.HEADER_TOKEN,
                    ConfigConstants.HEADER_TOKEN_PREFIX + BaseApplication.INSTANCE.token
                )
            }
            requestBuilder.headers(headersBuilder.build())
        }
        requestBuilder.url(urlBuilder.build())

        /*
        添加公共参数
        将原请求中的参数重新组织成定义好的入参格式，例如：
        {
            "sign": "签名信息",
            "oauth": "用户id",
            "body": {
                // 具体的参数
            }
        }
        */
        if (oldRequest.method() == "POST" && useCustomParams) {
            val requestBody = oldRequest.body()
            if (requestBody is FormBody) {
                val body = JSONObject()
                val paramsList = arrayListOf<String>()
                for (i in 0 until requestBody.size()) {
                    body.put(requestBody.name(i), requestBody.value(i))
                    paramsList.add(requestBody.name(i) + "=" + requestBody.value(i))
                }
                if (!oldRequest.url().uri().toString().endsWith("loginApp") && !oldRequest.url().uri().toString().endsWith(
                        "getVerifyCodeWhenLogin"
                    )
                ) {
                    // 根据参数名ASC码排序
                    var paramsArray = arrayOf<String>()
                    paramsArray = paramsList.toArray(paramsArray)
                    Arrays.sort(paramsArray, String.CASE_INSENSITIVE_ORDER)

                    // 拼接参数
                    val signStr = StringBuilder()
                    paramsArray.forEach {
                        signStr.append(it)
                        signStr.append("&")
                    }

                    signStr.append("key=")
                    signStr.append(HttpGlobalConfig.ENCRYPT_KEY)

                    LogUtils.d(TAG, "----------------$signStr")

                    // 加密生成签名
                    val sign = Encrypt.EnCode(signStr.toString(), Encrypt.MD5).toUpperCase()

                    val oauth = JSONObject()
                    oauth.put("userId", BaseApplication.INSTANCE.userId)


                    val json = JSONObject()
                    json.put("sign", sign)
                    json.put("oauth", oauth)
                    json.put("body", body)
                    requestBuilder.post(
                        RequestBody.create(
                            MediaType.parse("application/json; charset=utf-8"),
                            json.toString()
                        )
                    )
                } else {
                    // 登录接口
                    requestBuilder.post(
                        RequestBody.create(
                            MediaType.parse("application/json; charset=utf-8"),
                            body.toString()
                        )
                    )
                }
                return chain.proceed(requestBuilder.build())
            } else if (requestBody is MultipartBody) {
                LogUtils.d(TAG, "requestBody is MultipartBody")
            }
        }
        val newRequest: Request = requestBuilder.build()
        if (!(newRequest.body() is MultipartBody)) {
            try {
                val mediaType = newRequest.body()?.contentType()
                if (mediaType != null) {
                    val filed = mediaType::javaClass.get().getDeclaredField("mediaType")
                    filed.isAccessible = true
                    filed.set(mediaType, "application/json")
                }
            } catch (e: NoSuchFieldException) {
                LogUtils.e(TAG, e.message!!)
            } catch (e: IllegalAccessException) {
                LogUtils.e(TAG, e.message!!)
            }
        }

        return chain.proceed(newRequest)
    }
}